package bishi;

import java.util.concurrent.*;

// futureTask使用
public class demo3 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {

        // 1. 创建一个Callable任务
        Callable<Integer> expensiveCalculation = new Callable<Integer>(){
            @Override
            public Integer call() throws Exception {
                Thread.sleep(4000);
                return 42;
            }
        };

        // 2. 用FutureTask包装Callable任务
        FutureTask<Integer> futureTask = new FutureTask<>(expensiveCalculation);

        // 3. 创建线程池并提交任务
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(futureTask);

        System.out.println("主线程可以继续做其它事情了");
        Thread.sleep(1000);
        System.out.println("其他事情做完了，去获取结果.......");

        // 4. 获取异步任务的结果 (这会阻塞，直到计算完成)
        Integer result = futureTask.get();
        System.out.println("计算结果是：" + result);
        // 关闭线程池
        executorService.shutdown();

    }
}
